"use strict";

angular.module('app.sensor').controller('WatchChartsCtrl', function ($scope, $stateParams, $http, $cookieStore, $location) {
    //$scope.userid = $cookieStore.get('userid');
    $scope.fid = $cookieStore.get('userinfo').fid;
    //获得用户个人信息
    $http.get(baseurl + "/detail/user?id==" + $cookieStore.get("userid")).then(function (res) {
         $scope.company = res.data.info.name + "(" + res.data.info.id + ")"  + '公司的数据分析';
    })
    $scope.date = {};
    $scope.times = [
        { id: '1', name: "一天" },
        { id: '2', name: "一星期" },
        { id: '3', name: "一月" },
        { id: '4', name: "一年" },
        { id: '5', name: "两年" },
        { id: '6', name: "三年" }
    ];
    $scope.date.id = '3';
    var content = '';
    //获取当前时间加载到开始日期
    function today() {
        var today = new Date();
        var h = today.getFullYear();
        var m = today.getMonth() + 1;
        var d = today.getDate();
        return h + "-" +  m + "-" + d;
    }
    document.getElementById("startdate").value = today();
    $http.get(baseurl + '/select_idname/charts').then(function (res) {
        //console.log(res.data);
        if (res.data.ret == 1 && res.data.info.length > 0) {
            $scope.plans = res.data.info;
            if (res.data.info.length > 0) {
                $scope.planid = res.data.info[0].id + '';
                $scope.selectPlan($scope.planid);
            }
        }
    });
    if($stateParams.deviceid && $stateParams.deviceid !='' && $stateParams.deviceid != null ){
         $scope.deviceid = $stateParams.deviceid;
    }
    $http.get(baseurl + '/list_nopage/device').then(function (res) {
        if (res.data.ret == 1 && res.data.info.length > 0) {
            $scope.devices = res.data.info;
            if (res.data.info.length > 0) {
                if($stateParams.deviceid == null || $stateParams.deviceid == '' ){
                     $scope.deviceid = res.data.info[0].deviceid + '';
                }
            }
        }
    });
    //获取方案的字段
    $scope.field;
    $scope.type;
    $scope.plan_id;
    $scope.selectPlan = function (id) {
        $scope.plan_id = id;
        $http.get(baseurl + "/detail/charts?id==" + id).then(function (res) {
            if (res.data.ret == 1) {
                $scope.field1 = res.data.info.field;
                $scope.type = res.data.info.type;
                $scope.field = $scope.field1;
                if($stateParams.deviceid && $stateParams.deviceid !='' && $stateParams.deviceid != null ){
                     $scope.sure_query();
                }
            }
            $scope.sure_query();
        })
    };
    //隐藏数据表
    $scope.table = true;
    //确定查询
    var myChart1;
    var myChart2;
    var myChart3;
    if (myChart1 != null) {
        myChart1.clear();
    }
    if (myChart2 != null) {
        myChart2.clear();
    }
    if (myChart3 != null) {
        myChart3.clear();
    }
    var handle_table = [];
    $scope.sure_query = function (date) {
        //获取时间
        if (myChart1 != null)
            myChart1.clear();
        if (myChart2 != null)
            myChart2.clear();
        if (myChart3 != null)
            myChart3.clear();
        var startdate = $("#startdate").val();
        var enddate = $("#enddate").val();
        if ($scope.deviceid == '' || $scope.deviceid == undefined) {
            new Notify("info", '设备不能为空，请选择');
            return;
        }
        if ($scope.plan_id == '' || $scope.plan_id == undefined) {
            new Notify("info", '方案不能为空，请选择');
            return;
        }
        if (startdate == '' || startdate == null) {
            new Notify('info', '开始时间不能为空，请选择');
            return;
        }
        if (enddate == '' || enddate == undefined) {
            new Notify('info', '结束时间不能为空，请选择');
            return;
        }
        var query = $scope.deviceid + "&time=" + startdate + "&timetype=" + enddate + "&field=" + $scope.field;
        // console.log(query);
        $http.get(baseurl + "/history_curve_1?deviceid==" + query).then(function (res) {
            for (var i = 0 ; i < res.data.info.length; i++) {
                var obj = res.data.info[i];
                obj.time = obj.time + obj.unit;   
            }    
           
            if (res.data.ret == 1) {
                $scope.table = false;
            }
            var handle_data = res.data.info;
            chart_type($scope.type, $scope.field, handle_data);
            $scope.datas = res.data.info; // handle_num(res.data.info,$scope.field);
            $scope.arrField = [];
            $scope.arrField2 = [];
            var map_obj = handle_data[0];
            for (var key in map_obj) {
                var name = key;
                if (key == 'time') {
                    name = '时间';
                }
                if (key != 'unit') {
                    $scope.arrField.push(name);
                    $scope.arrField2.push(key);
                }
            };
            $scope.filedKey_name = $scope.arrField;
            $scope.filedKey = $scope.arrField2;
        });
    };
   
    //图表类型
    function chart_type(type, field, handle_data) {
        var types = type.split(',');
        var fields = field.split(',');
        if (types.length != fields.length) {
            console.log("error of type and field length is not equal");
            return null;
        }
        for (var i = 0; i < types.length; i++) {
            if (types[i] == 'line') {
                myChart1 = echarts.init(document.getElementById('line'));
                var option1 = chart_1(handle_data,fields[i]);
                myChart1.setOption(option1);
            }
            else if (types[i] == 'bar') {
                myChart2 = echarts.init(document.getElementById('bar'));
                var option2 = chart_2(handle_data,fields[i]);
                myChart2.setOption(option2);
            }
            else if (types[i] == 'pie') {
                myChart3 = echarts.init(document.getElementById('pie'));
                myChart3.clear();
                var option3 = chart_3(handle_data,fields[i]);
                myChart3.setOption(option3);
            }
        }
    };
    //处理时间 一个字段
    var handle_arr = function (arr, field) {
        var data = [];
        for (var i = 0; i < arr.length; i++) {
            var darray = [];
            var dd = parseFloat(arr[i][field]);
            dd = dd.toFixed(2);
            arr[i][field] = dd;
            var dt = arr[i].time;
            darray.push(dd);
            darray.push(dt);
            data.push(darray);
        }
        return data;
    };
    function get_type_field(xz){
        var t1 = $scope.type.split(',');
        var t2 = $scope.field.split(',');
        if (t1.length != t2.length)
            return null;
        var obj = {};
        for (var i = 0; i < t1.length; i++)
            obj[t1[i]] = t2[i];
        return obj;
    }

    //折线图
    function chart_1(handle_data,field) {
        //console.log(handle_data);
        var data = handle_arr(handle_data,field);
        var timeList = data.map(function (item) {
            return item[1];
        });
        var value2List = data.map(function (item) {
            return item[0];
        });
        var obj = get_type_field();
        if (obj == null) {
            //console.log("errir typefield is null");
            return;
        }
        $scope.type_value = obj.line; //JSON.parse($scope.type_field).line;
        var option1 = {
            title: {
                text: ''
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: [$scope.type_value]
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: timeList,
                name: ''
            },
            yAxis: {
                type: 'value',
                data: value2List
            },
            series: [
                {
                    name: $scope.type_value,
                    type: 'line',
                    stack: '总量',
                    data: value2List
                },
            ]
        };
        return option1;
    }
    // 柱状图
    function chart_2(handle_data,field) {
        var data = handle_arr(handle_data,field);
        var timeList = data.map(function (item) {
            //console.log(item);
            return item[1];
        });
        var value1List = data.map(function (item) {
            return item[0];
        });
        var obj = get_type_field();
        if (obj == null) {
            //console.log("errir typefield is null");
            return;
        }
        $scope.type_value = obj.bar; 
        var option2 = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            legend: {
                data: [$scope.type_value]
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'value',
                data: value1List
            },
            yAxis: {
                type: 'category',
                data: timeList
            },
            series: [
                {
                    name: $scope.type_value,
                    type: 'bar',
                    stack: '总量',
                    label: {
                        normal: {
                            show: true,
                            position: 'insideRight'
                        }
                    },
                    data: value1List
                }
            ]
        };
        return option2;
    }
    //2end
    //饼图
    function chart_3(handle_data,field) {
        var handle_data_1 = handle_arr(handle_data, field);
        var arr2 = [];
        var obj = get_type_field();
        if (obj == null) {
            //console.log("errir typefield is null");
            return;
        }
        $scope.type_value = obj.pie; //JSON.parse($scope.type_field).line;

        //$scope.type_value = JSON.parse($scope.type_field).pie;
        for (var i = 0; i < handle_data_1.length; i++) {
            var arr = handle_data_1[i];
            var obj = {};
            obj.value = arr[0];
            obj.name  = arr[1];
            arr2.push(obj);
        }
        var option3 = {
             title: {
                 text: '',
                 subtext: '',
                 x: 'center'
             },
             tooltip: {
                 trigger: 'item',
                 formatter: "{a} <br/>{b} : {c} ({d}%)"
             },
             legend: {
                 orient: 'vertical',
                 left: 'left',
                 data: [$scope.type_value]
             },
             series: [
                 {
                     name: $scope.type_value,
                     type: 'pie',
                     radius: '55%',
                     center: ['50%', '60%'],
                     data: arr2,
                     itemStyle: {
                         emphasis: {
                             shadowBlur: 10,
                             shadowOffsetX: 0,
                             shadowColor: 'rgba(0, 0, 0, 0.5)'
                         }
                     }
                 }
             ]
        };
        return option3;
    }
    //3end
})